//
//  Reg1ViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/20.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//
#import "Reg1ViewController.h"
#import "Reg3ViewController.h"
#import "Reg2ViewController.h"
#import "LoginViewController.h"
#import "JKCountDownButton.h"
#import "CommonPickerViewController.h"
@interface Reg3ViewController ()<CommonPickerDelegate>

@property (nonatomic, strong) NSArray *_cityList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic, strong) CommonPickerViewController *picker;
@property (nonatomic, strong) NetworkManager *networkManager;

@property (weak, nonatomic) IBOutlet UILabel *xiaoquLbl;
@property (weak, nonatomic) IBOutlet UILabel *zhuhuIdLbl;
@property (weak, nonatomic) IBOutlet UILabel *userIdLbl;
@property (weak, nonatomic) IBOutlet UITextField *nicknameTxt;

@property (nonatomic, strong) NSMutableArray *componentData;
@property (nonatomic, strong) NSMutableArray *cityIdData;
@property (nonatomic, strong) NSMutableArray *xiaoquData;
@property (nonatomic, strong) NSMutableArray *xiaoquIdData;
@property (nonatomic, strong) NSString *city_id;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, assign) CGRect contentPreFrame;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@end

@implementation Reg3ViewController
@synthesize check2 = _check2;
@synthesize check3 = _check3;
@synthesize check4 = _check4;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    [super viewDidLoad];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    
    [self addKeyboardNotificationForTarget:self];
    CGRect frame = self.contentView.frame;
    self.contentPreFrame = frame;
    
    //定义一个toolBar
    UIToolbar
    * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    //设置style
    [topView
     setBarStyle:UIBarStyleBlack];
    //定义两个flexibleSpace的button，放在toolBar上，这样完成按钮就会在最右边
    
    UIBarButtonItem
    * button1 =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem
    * button2 = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //定义完成按钮
    UIBarButtonItem
    * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成"style:UIBarButtonItemStyleDone
                                                  target:self action:@selector(resignKeyboard)];
    
    //在toolBar上加上这些按钮
    NSArray
    * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
    
    [topView
     setItems:buttonsArray];
    
    [self.nicknameTxt setInputAccessoryView:topView];
    
    _check3 = [[QCheckBox alloc] initWithDelegate:self];
    _check3.frame = CGRectMake(100, 375, 100, 50);
    [_check3 setTitle:@"" forState:UIControlStateNormal];
    [_check3 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_check3.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
    [self.view addSubview:_check3];
    
    _check4 = [[QCheckBox alloc] initWithDelegate:self];
    _check4.frame = CGRectMake(200, 375, 100, 50);
    [_check4 setTitle:@"" forState:UIControlStateNormal];
    [_check4 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_check4.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
    [self.view addSubview:_check4];
    
}

//添加键盘监听事件
- (void)addKeyboardNotificationForTarget:(id)observer {
    //监听键盘切换
    [[NSNotificationCenter defaultCenter] addObserver:observer
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:observer
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    //判断iphone版本,ios5中文键盘高度有改变，需要相应调整UI
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:observer
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillChangeFrameNotification
                                                   object:nil];
    }
#endif
}

//监听键盘出现、消失和改变大小的事件。当切换至中文键盘，键盘高度改变时相应的改变键盘上方的控件
- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    CGRect frame = self.contentPreFrame;
    self.contentView.frame = CGRectMake(frame.origin.x, frame.origin.y - 270,
                                        frame.size.width, frame.size.height);
    
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification*)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.contentView.frame = self.contentPreFrame;
    
    [UIView commitAnimations];
}

-(void)resignKeyboard
{
    [self.nicknameTxt resignFirstResponder];
    
}

- (IBAction)backToPre:(id)sender {
    Reg1ViewController *problemVC = (Reg1ViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"Reg1ViewController"];
    
    CATransition* transition = [CATransition animation];
    transition.type = kCATransitionPush;//可更改为其他方式
    transition.subtype = kCATransitionFromRight;//可更改为其他方式
    
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    
    [self.navigationController pushViewController:problemVC animated:NO];
}

- (IBAction)showInfo:(id)sender {
    if([self.xiaoquLbl.text isEqualToString:@"暂无匹配，请与物业联系"]){
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:self.xiaoquLbl.text
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
}

- (IBAction)next:(id)sender {
    if(_check2 != nil && !_check2.checked){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请匹配房屋信息"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    } else if(![self.nicknameTxt hasText]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请先填写昵称"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
        
    }
    else {
        if (self.networkManager == nil) {
            self.networkManager = [[NetworkManager alloc] init];
        }
        
        NSString *sexStr = @"1";
        if(_check4.checked){
            sexStr = @"0";
        }
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               self.zhuhuIdLbl.text,@"zhuhu_id", self.userIdLbl.text,@"user_id",self.nicknameTxt.text,@"nick_name",sexStr,@"sex",nil];
        [self.networkManager requestWithMethod:identityVerification parameter:param delegate:self];
        [self.HUD show:YES];
        
    }
}

- (void)didSelectedCheckBox:(QCheckBox *)checkbox checked:(BOOL)checked {
    if(_check3.checked){
        _check4.checked = nil;
    } else if(_check4.checked){
        _check3.checked = nil;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           _phone,@"phone", nil];
    [self.networkManager requestWithMethod:getZhuhuListByPhone parameter:param delegate:self];
    [self.HUD show:YES];
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    if (methodId == getZhuhuListByPhone) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            NSString * vercode = [data objectForKeyOrNil:@"resultinfo"];
            self.userIdLbl.text = [[data objectForKeyOrNil:@"userId"] stringValue];
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"zhuhuList"];
                NSString *stringAll =@"";
                NSString *zhuhuidAll =@"";
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    for(id obj in results){
                        NSString *louStr = [[obj objectForKeyOrNil:@"lou"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *xiaoquStr = [[obj objectForKeyOrNil:@"xiaoqu"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *menpaiStr = [[obj objectForKeyOrNil:@"menpai"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                       
                        stringAll =  [stringAll stringByAppendingFormat:@"%@/%@/%@\n",xiaoquStr, louStr, menpaiStr ];
                        zhuhuidAll = [zhuhuidAll stringByAppendingFormat:@"%@,",[[obj objectForKeyOrNil:@"zhuhuId" ] stringValue] ] ;
                    }
                    self.xiaoquLbl.text = stringAll;
                    self.zhuhuIdLbl.text = zhuhuidAll;
                    _check2 = [[QCheckBox alloc] initWithDelegate:self];
                    _check2.frame = CGRectMake(300, 225, 100, 50);
                    [_check2 setTitle:@"" forState:UIControlStateNormal];
                    [_check2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                    [_check2.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
                    [self.view addSubview:_check2];
                }
            }
        }
        
    } else if (methodId == identityVerification) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            NSString * vercode = [data objectForKeyOrNil:@"resultinfo"];
            if([result isEqualToString:@"000"]){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"恭喜您注册成为智慧管家的会员！"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                LoginViewController *problemVC = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
                UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:problemVC];
                DDMenuController *menuVC = [[DDMenuController alloc] initWithRootViewController:navController];
//                [self presentViewController:menuVC animated:YES completion:^{}];
                [self.navigationController pushViewController:menuVC animated:YES];
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

@end